package handler

import (
	"context"
	"encoding/json"
	"errors"
	pb "mpps/services/srv-ProgramList/proto"
	common "mpps/tools/common"
	"mpps/tools/repository/dao"
	"mpps/tools/repository/dao/program"
)

type ProgramList struct {
}

func NewProgramList() *ProgramList {
	return &ProgramList{}
}

// Call is a single request handler called via client.Call or the generated client code
func (c *ProgramList) Call(ctx context.Context, req *pb.Request, rsp *pb.Response) error {
	if len(req.Mode) <= 0 || len(req.FileType) <= 0 {
		return errors.New(common.ErrParamsValidation.Message)
	}
	if req.FileType != program.Js.String() && req.FileType != program.Program.String() {
		return errors.New(common.ErrParamsValidation.Message)
	}
	if req.Mode != program.Dev.String() && req.Mode != program.Preview.String() && req.Mode != program.Prod.String() {
		return errors.New(common.ErrParamsValidation.Message)
	}
	if req.CurrPage <= 0 {
		req.CurrPage = 1
	}
	if req.PageSize <= 0 {
		req.PageSize = 20
	}
	list := make([]program.MiniProgram, 0)
	where := program.MiniProgram{}
	rb, _ := json.Marshal(req)
	json.Unmarshal(rb, &where)
	result := dao.GetDB(ctx).
		Model(&program.MiniProgram{}).
		Where(where).
		Order("created_at desc").
		Limit(int(req.PageSize)).
		Offset(int((req.CurrPage - 1) * req.PageSize)).
		Find(&list)
	var count int64
	dao.GetDB(ctx).
		Model(&program.MiniProgram{}).
		Where(where).
		Count(&count)
	if result.RowsAffected > 0 {
		rsp.CurrPage = req.CurrPage
		rsp.PageSize = req.PageSize
		rsp.Total = count
		for _, v := range list {
			pinfo := &pb.ProgramInfo{
				ProgramId: v.ProgramId,
				Mode:      v.Mode,
				FileName:  v.FileName,
				FileType:  v.FileType,
				FileId:    v.FileId,
				Version:   v.Version,
			}
			rsp.ChildList = append(rsp.ChildList, pinfo)
		}
	}
	return nil
}
